//
//  DataFactory.m
//  Ghac 4S
//
//  Created by apple on 11-9-2.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "DataFactory.h"
#import "LocalDataProvider.h"
#import "NetDataProvider.h"
@interface DataFactory(private)
-(void)askForData:(NSString *)type byWay:(NSString *)way;
@end

@implementation DataFactory
@synthesize orderType = m_currentType;
-(id)init
{
    
    if ((self = [super init]))
    {
        NSString* filePath = [[NSBundle mainBundle] pathForResource:@"Property List" ofType:@"plist"];
        m_plistData = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
//        NSLog(@"%@", m_plistData);
    }
    return self;
}
-(DataProvide *)produceProviderWithDelegate:(id<DataProvideProtocol>)delegate
{
    if (m_dataProvider != Nil)
    {
        [m_dataProvider release];
    }
    m_delegate = delegate;
    m_dataProvider = [[LocalDataProvider alloc] initWithDelegate:self];
    return m_dataProvider;
}
-(void)askDatas:(NSString *)type
{
    
    m_currentWay = DF_SOURCETYPE_LOCAL;
    [self askForData:type byWay:m_currentWay];
}
-(void)askForData:(NSString *)type byWay:(NSString *)way
{
    self.orderType = type;
    NSString* str = [[[m_plistData objectForKey:@"EntryBtn"] objectForKey:type] objectForKey:way];
    str = [str stringByExpandingTildeInPath];
    [m_dataProvider loadDataWithResource:str];
}
-(void)onData:(id)sender
{ 
    NSString* str = [[NSString alloc] initWithData:sender encoding:NSUTF8StringEncoding];
    if ([m_dataProvider isMemberOfClass:[NetDataProvider class]])
    {
       
        NSString* path = [[[m_plistData objectForKey:@"EntryBtn"] objectForKey:self.orderType] objectForKey:DF_SOURCETYPE_LOCAL];
        NSString*   realPath = [path stringByExpandingTildeInPath];
        BOOL b = [str writeToFile:realPath atomically:YES encoding:NSUTF8StringEncoding error:Nil];
       
        [path release];
        NSLog(@"write to file @ path:%@, %d", realPath, b);
    }
    if(m_delegate != Nil)
    {
        [m_delegate onData:sender];
    }
     [str release];
    
}
-(void)onError:(id)sender
{
    if ([m_dataProvider isMemberOfClass:[LocalDataProvider class]])
    {
        NSLog(@"local fail and retry @ net work");
//        m_currentWay = DF_SOURCETYPE_NETWORK;
        [m_dataProvider release];
        m_dataProvider = [[NetDataProvider alloc] initWithDelegate:self];
        [self askForData:self.orderType byWay:DF_SOURCETYPE_NETWORK];
    }
    else if ([m_dataProvider isMemberOfClass:[NetDataProvider class]])
    {
        if(m_delegate != Nil)
        {
            [m_delegate onError:Nil];
        }
    }
}
+(DataFactory *)sharedDataFactory
{
    if (g_dataFactory == Nil)
    {
        g_dataFactory = [[DataFactory alloc] init];
    }
    return g_dataFactory;
//    return [[[DataFactory alloc] init] autorelease];
}
-(void)dealloc
{
    if (m_dataProvider != Nil)
    {
        [m_dataProvider release];
    }
    [super dealloc];
}
@end
